#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

#include "app_baidu_authen.h"
#include "global_config.h"



extern String token;


// 构建token请求URL的函数
static String buildTokenURL() {
  String url = "https://aip.baidubce.com/oauth/2.0/token";
  url += "?grant_type=" + String(GRANT_TYPE);
  url += "&client_id=" + String(CLIENT_ID);
  url += "&client_secret=" + String(CLIENT_SECRET);
  return url;
}


static void parseTokenResponse(String jsonString) {
  // 使用ArduinoJson解析响应
  DynamicJsonDocument doc(1024);
  DeserializationError error = deserializeJson(doc, jsonString);
  
  if (error) {
    Serial.print("JSON解析失败: ");
    Serial.println(error.c_str());
    return;
  }
  
  // 提取access_token
  if (doc.containsKey("access_token")) {
    const char* access_token = doc["access_token"];
    int expires_in = doc["expires_in"];
    
    Serial.println("=== Baidu API Token获取成功 ===");
    Serial.printf("Access Token: %s\n", access_token);
    token = access_token;//直接赋值
    Serial.printf("Expires in: %d seconds\n", expires_in);
    Serial.printf("Token Type: %s\n", doc["token_type"] | "unknown");
    //Serial.printf("Scope: %s\n", doc["scope"] | "unknown");
    Serial.println("==============================");
    
    // 这里可以将token保存到变量中供后续使用
    // global_access_token = String(access_token);
    
  } else if (doc.containsKey("error")) {
    const char* error_msg = doc["error_description"];
    Serial.println("=== Baidu API Token获取失败 ===");
    Serial.printf("Error: %s\n", doc["error"] | "unknown");
    Serial.printf("Error Description: %s\n", error_msg);
    Serial.println("==============================");
  }
}




void getBaiduToken() {
  HTTPClient http;
  
  // 构建请求URL（包含所有查询参数）
  String token_url = buildTokenURL();
  Serial.println("Request URL: " + token_url);
  
  // 开始HTTP连接
  http.begin(token_url);
  
  // 设置HTTP头
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Accept", "application/json");
  
  Serial.println("Sending POST request to Baidu API...");
  
  // 发送POST请求，请求体为空（因为参数都在URL中）
  int httpResponseCode = http.POST("");
  
  // 检查响应
  if (httpResponseCode > 0) {
    Serial.printf("HTTP Response code: %d\n", httpResponseCode);
    
    // 获取响应内容
    String response = http.getString();
    //Serial.println("Response: " + response);   //暂时不打印内容
    
    // 解析JSON响应
    parseTokenResponse(response);
    
  } else {
    Serial.printf("Error code: %d\n", httpResponseCode);
    Serial.println("Error: " + http.errorToString(httpResponseCode));
  }
  
  // 释放资源
  http.end();
}
